import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _uniqWith from "lodash/uniqWith";
import _remove from "lodash/remove";
import _isUndefined from "lodash/isUndefined";
import _isString from "lodash/isString";
import _isObject from "lodash/isObject";
var _excluded = ["fileList", "fileType", "fileSize", "single", "text", "listType", "bucketName", "onUploadSuccess", "onUploadError", "viewOnly", "showRemoveIcon", "docType", "storageCode", "children"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _class;

/**
 * 上传按钮组件.
 * CHANGELOG: 2019-06-20: 过滤上传错误的文件时同时过滤掉 没有 uid 的文件, 文件 onChange 统一过滤掉 uid 重复的文件
 *
 * @date: 2018-7-13

 */
import React from 'react';
import { Button, Icon, notification, Upload } from 'antd';
import { Bind } from 'lodash-decorators';
import AbortController from 'abort-controller';
import intl from "../../utils/intl";
import request from "../../utils/request";
import { getAccessToken, getAttachmentUrl, getCurrentOrganizationId, getResponse, isTenantRoleLevel } from "../../utils/utils";
import { getEnvConfig } from "../../utils/iocUtils";
import { removeUploadFile } from "../../services/api";
notification.config({
  placement: 'bottomRight'
});
var UploadButton = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(UploadButton, _React$Component);

  var _super = _createSuper(UploadButton);

  function UploadButton(props) {
    var _this;

    _classCallCheck(this, UploadButton);

    _this = _super.call(this, props);
    var onRef = _this.props.onRef;
    if (onRef) onRef(_assertThisInitialized(_this));
    _this.state = {
      fileList: null
    };
    _this.config = getEnvConfig();
    return _this;
  } // static getDerivedStateFromProps(props, state) {
  //   if (props.fileList.length > 0 && state.fileList == null) {
  //     return {
  //       fileList: props.fileList,
  //     };
  //   }
  //   return state;
  // }


  _createClass(UploadButton, [{
    key: "setFileList",
    value: function setFileList(fileList) {
      if (fileList) {
        this.setState({
          fileList: fileList
        });
      }
    }
  }, {
    key: "uploadData",
    value: function uploadData(file) {
      var _this$props = this.props,
          attachmentUUID = _this$props.attachmentUUID,
          bucketName = _this$props.bucketName,
          uploadData = _this$props.uploadData,
          bucketDirectory = _this$props.bucketDirectory,
          docType = _this$props.docType,
          storageCode = _this$props.storageCode;
      var data = uploadData ? uploadData(file) : {};

      if (!(data instanceof FormData)) {
        var currentData = data;
        data = new FormData();

        if (_isObject(data)) {
          Object.keys(currentData).forEach(function (paramKey) {
            data.append(paramKey, currentData[paramKey]);
          });
        }
      }

      if (!_isUndefined(attachmentUUID)) {
        data.append('attachmentUUID', attachmentUUID);
      }

      if (!_isUndefined(bucketName)) {
        data.append('bucketName', bucketName);
      }

      if (!_isUndefined(docType)) {
        data.append('docType', docType);
      }

      if (!_isUndefined(storageCode)) {
        data.append('storageCode', storageCode);
      }

      if (!_isUndefined(bucketDirectory)) {
        data.append('directory', bucketDirectory);
      } // data.append('fileName', file.name);


      return data;
    }
  }, {
    key: "onChange",
    value: function onChange(_ref) {
      var file = _ref.file,
          fileList = _ref.fileList;
      var _this$props2 = this.props,
          _this$props2$single = _this$props2.single,
          single = _this$props2$single === void 0 ? false : _this$props2$single,
          tenantId = _this$props2.tenantId,
          bucketName = _this$props2.bucketName,
          bucketDirectory = _this$props2.bucketDirectory;

      var list = _toConsumableArray(fileList);

      if (file.status === 'done') {
        var response = file.response;

        if (response && response.failed === true) {
          this.onUploadError(file, fileList);
        } else {
          if (single) {
            if (fileList.length > 1) {
              var onRemove = this.props.onRemove;
              Promise.all(fileList.slice(0, fileList.length - 1).map( /*#__PURE__*/function () {
                var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(fileItem) {
                  var splitDatas, fileUrl;
                  return _regeneratorRuntime.wrap(function _callee$(_context) {
                    while (1) {
                      switch (_context.prev = _context.next) {
                        case 0:
                          if (!fileItem.url) {
                            _context.next = 20;
                            break;
                          }

                          if (!onRemove) {
                            _context.next = 11;
                            break;
                          }

                          _context.prev = 2;
                          _context.next = 5;
                          return onRemove(fileItem);

                        case 5:
                          _context.next = 9;
                          break;

                        case 7:
                          _context.prev = 7;
                          _context.t0 = _context["catch"](2);

                        case 9:
                          _context.next = 20;
                          break;

                        case 11:
                          splitDatas = fileItem.url && fileItem.url.split('=') || [];
                          fileUrl = splitDatas[splitDatas.length - 1];
                          _context.prev = 13;
                          _context.next = 16;
                          return removeUploadFile({
                            tenantId: tenantId,
                            bucketName: bucketName,
                            urls: [fileUrl]
                          });

                        case 16:
                          _context.next = 20;
                          break;

                        case 18:
                          _context.prev = 18;
                          _context.t1 = _context["catch"](13);

                        case 20:
                        case "end":
                          return _context.stop();
                      }
                    }
                  }, _callee, null, [[2, 7], [13, 18]]);
                }));

                return function (_x) {
                  return _ref2.apply(this, arguments);
                };
              }())).catch(function () {// 单文件 上传成功后 删除之前的问题，报错不用管
              });
            }

            list = [{
              uid: file.uid,
              name: file.name,
              url: getAttachmentUrl(file.response, bucketName, tenantId, bucketDirectory),
              thumbUrl: getAttachmentUrl(file.response, bucketName, tenantId, bucketDirectory)
            }];
          } else {
            list = fileList.map(function (f) {
              if (f.uid === file.uid) {
                // f.url = file.response;
                // eslint-disable-next-line
                f.url = getAttachmentUrl(f.response, bucketName, tenantId, bucketDirectory); // f.url = `${CPAAS_FILE}/v1${
                //   !isUndefined(tenantId) ? `/${tenantId}/` : '/'
                // }files/redirect-url?access_token=${accessToken}&bucketName=${bucketName}${
                //   !isUndefined(bucketDirectory) ? `&directory=${bucketDirectory}&` : '&'
                // }url=${f.response}`;
              }

              return f;
            });
          }

          this.onUploadSuccess(file, list);
        }
      } else if (file.status === 'error') {
        this.onUploadError(file, fileList);
        list = fileList.filter(function (f) {
          return f.status !== 'error' && f.uid;
        });
      }

      this.setState({
        fileList: _uniqWith(list, function (r1, r2) {
          return r1.uid === r2.uid;
        })
      });
    }
  }, {
    key: "beforeUpload",
    value: function beforeUpload(file) {
      var _this$props3 = this.props,
          fileType = _this$props3.fileType,
          _this$props3$fileSize = _this$props3.fileSize,
          fileSize = _this$props3$fileSize === void 0 ? 30 * 1024 * 1024 : _this$props3$fileSize;

      if (fileType && fileType.indexOf(file.type) === -1) {
        file.status = 'error'; // eslint-disable-line

        var res = {
          message: intl.get('cpaas.common.upload.error.type', {
            fileType: fileType
          }).d("\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B\u5FC5\u987B\u662F\uFF1A".concat(fileType))
        };
        file.response = res; // eslint-disable-line

        return false;
      } // TODO 去掉文件 mimeType 校验
      // if (!file.type) {
      //   file.status = 'error'; // eslint-disable-line
      //   const res = {
      //     message: intl.get('cpaas.common.upload.error.type.null').d('上传文件类型缺失，请检查类型'),
      //   };
      //   file.response = res; // eslint-disable-line
      //   return false;
      // }


      if (file.size > fileSize) {
        file.status = 'error'; // eslint-disable-line

        var _res = {
          message: intl.get('cpaas.common.upload.error.size', {
            fileSize: fileSize / (1024 * 1024)
          }).d("\u4E0A\u4F20\u6587\u4EF6\u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC7: ".concat(fileSize / (1024 * 1024), " MB"))
        };
        file.response = _res; // eslint-disable-line

        return false;
      }

      return true;
    }
  }, {
    key: "onRemove",
    value: function onRemove(file) {
      var _this2 = this;

      var _this$props4 = this.props,
          onRemove = _this$props4.onRemove,
          bucketName = _this$props4.bucketName,
          onRemoveSuccess = _this$props4.onRemoveSuccess,
          _this$props4$single = _this$props4.single,
          single = _this$props4$single === void 0 ? false : _this$props4$single,
          tenantId = _this$props4.tenantId;
      var fileList = this.state.fileList;

      if (file.url) {
        if (onRemove) {
          return onRemove(file);
        }

        var splitDatas = file.url && file.url.split('=') || [];
        var fileUrl = splitDatas[splitDatas.length - 1];
        return removeUploadFile({
          tenantId: tenantId,
          bucketName: bucketName,
          urls: [fileUrl]
        }).then(function (res) {
          if (getResponse(res)) {
            if (onRemoveSuccess) {
              onRemoveSuccess();
            }

            if (single) {
              _this2.setState({
                fileList: []
              });
            } else {
              _remove(fileList, function (n) {
                return n.uid === file.uid;
              });

              _this2.setState({
                fileList: fileList
              });
            }

            return true;
          }

          return false;
        });
      }

      this.setState({
        fileList: fileList.filter(function (list) {
          return list.uid !== file.uid;
        })
      });
    }
  }, {
    key: "onUploadSuccess",
    value: function onUploadSuccess(file, fileList) {
      var onUploadSuccess = this.props.onUploadSuccess;
      if (onUploadSuccess) onUploadSuccess(file, fileList);
    }
  }, {
    key: "onUploadError",
    value: function onUploadError(file, fileList) {
      var onUploadError = this.props.onUploadError;
      var showTip = true;

      if (onUploadError) {
        showTip = onUploadError(file, fileList) !== false;
      }

      if (showTip) {
        notification.error({
          message: intl.get('cpaas.common.upload.status.error').d('上传失败'),
          description: file.response && file.response.message
        });
      }
    }
  }, {
    key: "changeFileList",
    value: function changeFileList(fileList) {
      var _this$props5 = this.props,
          bucketName = _this$props5.bucketName,
          bucketDirectory = _this$props5.bucketDirectory,
          tenantId = _this$props5.tenantId;

      if (fileList) {
        return fileList.map(function (res) {
          return _objectSpread(_objectSpread({}, res), {}, {
            url: getAttachmentUrl(res.url, bucketName, tenantId, bucketDirectory)
          });
        });
      }
    }
    /**
     * 由于需要 将其他参数放到 formData 中, 所有 action 变成 方法
     * @returns {*}
     */

  }, {
    key: "handleAction",
    value: function handleAction(_ref3) {
      var file = _ref3.file,
          onProgress = _ref3.onProgress,
          onSuccess = _ref3.onSuccess,
          onError = _ref3.onError;
      var controller = new AbortController();
      var signal = controller.signal;
      var CPAAS_FILE = this.config.CPAAS_FILE;
      var propAction = this.props.action;
      var actionPathname = propAction || (isTenantRoleLevel() ? "".concat(CPAAS_FILE, "/v1/").concat(getCurrentOrganizationId(), "/files/multipart") : "".concat(CPAAS_FILE, "/v1/files/multipart"));
      var action = "".concat(actionPathname);
      var data = this.uploadData(file); // data.set('file', file, file.name);

      data.append('file', file, file.name);
      request(action, {
        processData: false,
        // 不会将 data 参数序列化字符串
        method: 'POST',
        type: 'FORM',
        body: data,
        responseType: 'text',
        signal: signal,
        // 用于控制 取消 请求
        onProgress: onProgress ? function (e) {
          return onProgress(e, file);
        } : null
      }, {
        beforeCatch: function beforeCatch(err) {
          if (err.name === 'AbortError') {// 隐藏掉 取消上传的 fetch 报错
          } else {
            throw new Error(err);
          }
        }
      }).then(function (res) {
        if (_isString(res)) {
          // 成功
          onSuccess(res);
        } else if (!getResponse(res)) {
          onError(res); // 失败
        }
      });
      return {
        abort: function abort() {
          controller.abort();
        }
      };
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props6 = this.props,
          fileList = _this$props6.fileList,
          fileType = _this$props6.fileType,
          fileSize = _this$props6.fileSize,
          single = _this$props6.single,
          _this$props6$text = _this$props6.text,
          text = _this$props6$text === void 0 ? intl.get('cpaas.common.upload.txt').d('上传') : _this$props6$text,
          _this$props6$listType = _this$props6.listType,
          listType = _this$props6$listType === void 0 ? 'picture' : _this$props6$listType,
          bucketName = _this$props6.bucketName,
          onUploadSuccess = _this$props6.onUploadSuccess,
          onUploadError = _this$props6.onUploadError,
          _this$props6$viewOnly = _this$props6.viewOnly,
          viewOnly = _this$props6$viewOnly === void 0 ? false : _this$props6$viewOnly,
          _this$props6$showRemo = _this$props6.showRemoveIcon,
          showRemoveIcon = _this$props6$showRemo === void 0 ? true : _this$props6$showRemo,
          docType = _this$props6.docType,
          storageCode = _this$props6.storageCode,
          children = _this$props6.children,
          otherProps = _objectWithoutProperties(_this$props6, _excluded);

      var accessToken = getAccessToken();
      var changedFileList = this.changeFileList(fileList);
      var headers = {};

      if (accessToken) {
        headers.Authorization = "bearer ".concat(accessToken);
      }

      var acceptFileType = fileType && fileType.indexOf(',') === -1 ? fileType.split(';').join(',') : fileType;
      var uploadButton;

      if (listType === 'picture-card') {
        uploadButton = /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Icon, {
          style: {
            fontSize: '32px',
            color: '#999'
          },
          type: "plus"
        }));
      } else {
        uploadButton = /*#__PURE__*/React.createElement(Button, null, /*#__PURE__*/React.createElement(Icon, {
          type: "upload"
        }), " ", text);
      }

      return /*#__PURE__*/React.createElement(Upload, Object.assign({
        name: "file",
        accept: acceptFileType,
        fileList: this.state.fileList || changedFileList,
        data: this.uploadData,
        customRequest: this.handleAction,
        headers: headers,
        onChange: this.onChange,
        listType: listType,
        beforeUpload: this.beforeUpload,
        onRemove: this.onRemove,
        showUploadList: {
          showRemoveIcon: !viewOnly && showRemoveIcon
        }
      }, otherProps), children || !viewOnly && uploadButton);
    }
  }]);

  return UploadButton;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "uploadData", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "uploadData"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onChange", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "onChange"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "beforeUpload", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "beforeUpload"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onRemove", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "onRemove"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "changeFileList", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "changeFileList"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleAction", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "handleAction"), _class.prototype)), _class));
export { UploadButton as default };